#include "managerswin.h"
#include "ui_managerswin.h"
#include "part1.h"
#include <QDateTime>
#include <QSqlError>
#include <QSqlRecord>
#include <QHBoxLayout>
#include <QSpinBox>
#include <QLabel>

managerswin::managerswin(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::managerswin),
    model(new QStandardItemModel(this)),
    currentPage(1),
    pageSize(10),
    totalItems(0),
    currentTable("packages")
{
    ui->setupUi(this);

    // Setup table view
    ui->ListTable->setModel(model);

    // Set window title
    setWindowTitle("物流管理系统 - 管理员界面");

    // Setup pagination controls
    setupPagination();

    // Initialize database
    if (!initDatabase()) {
        QMessageBox::critical(this, "数据库错误", "无法连接到数据库");
    }

    // Initialize with package list by default
    loadPackagesIntoTable();
}

managerswin::~managerswin()
{
    // Close database connection
    if (sqlDb.isOpen()) {
        sqlDb.close();
    }

    delete ui;
    delete model;
}

// Initialize database connection
bool managerswin::initDatabase()
{
    sqlDb = QSqlDatabase::addDatabase("QSQLITE");
    sqlDb.setDatabaseName("packages.db");

    if (!sqlDb.open()) {
        QMessageBox::critical(this, "数据库连接错误",
                              "无法打开数据库: " + sqlDb.lastError().text());
        return false;
    }

    return true;
}

// Set manager info in the UI
void managerswin::setManagerInfo(const QString &username)
{
    ui->managersnameline->setText(username);
}

// Setup pagination controls
void managerswin::setupPagination()
{
    // Previous page button
    connect(ui->prevPageBtn, &QPushButton::clicked, this, &managerswin::onPrevPageClicked);

    // Page number display and input
    ui->pageSpinBox->setMinimum(1);
    ui->pageSpinBox->setValue(currentPage);
    connect(ui->pageSpinBox, &QSpinBox::valueChanged, this, &managerswin::onPageNumberChanged);

    // Next page button
    connect(ui->nextPageBtn, &QPushButton::clicked, this, &managerswin::onNextPageClicked);

}

// Update pagination controls based on current data
void managerswin::updatePagination()
{
    int totalPages = calculateTotalPages();

    // Update total pages label
    if (ui->totalPagesLabel) {
        ui->totalPagesLabel->setText(QString("/ %1").arg(totalPages));
    }

    // Update spinbox max value
    if (ui->pageSpinBox) {
        ui->pageSpinBox->setMaximum(totalPages > 0 ? totalPages : 1);
        ui->pageSpinBox->setValue(currentPage);
    }

    updatePageNavigationStatus();
}

// Calculate total pages based on item count and page size
int managerswin::calculateTotalPages()
{
    return (totalItems + pageSize - 1) / pageSize;
}

// Update the enabled status of navigation buttons
void managerswin::updatePageNavigationStatus()
{
    int totalPages = calculateTotalPages();

    ui->prevPageBtn->setEnabled(currentPage > 1);
    ui->nextPageBtn->setEnabled(currentPage < totalPages);
}

// Navigation button handlers
void managerswin::onPrevPageClicked()
{
    if (currentPage > 1) {
        currentPage--;

        if (currentTable == "packages") {
            loadPackagesIntoTable();
        } else if (currentTable == "orders") {
            loadOrdersIntoTable();
        } else if (currentTable == "users") {
            loadUsersIntoTable();
        }
    }
}

void managerswin::onNextPageClicked()
{
    int totalPages = calculateTotalPages();
    if (currentPage < totalPages) {
        currentPage++;

        if (currentTable == "packages") {
            loadPackagesIntoTable();
        } else if (currentTable == "orders") {
            loadOrdersIntoTable();
        } else if (currentTable == "users") {
            loadUsersIntoTable();
        }
    }
}

void managerswin::onPageNumberChanged(int page)
{
    if (page != currentPage) {
        currentPage = page;

        if (currentTable == "packages") {
            loadPackagesIntoTable();
        } else if (currentTable == "orders") {
            loadOrdersIntoTable();
        } else if (currentTable == "users") {
            loadUsersIntoTable();
        }
    }
}

// Load packages into table with pagination
void managerswin::loadPackagesIntoTable()
{
    // Set current table
    currentTable = "packages";

    // Clear the model
    model->clear();

    // Set headers
    QStringList headers;
    headers << "订单编号" << "发件人" << "收件人" << "状态" << "取件码";
    model->setHorizontalHeaderLabels(headers);

    // First query to get total count
    QSqlQuery countQuery(sqlDb);
    countQuery.prepare("SELECT COUNT(*) FROM packages");

    if (!countQuery.exec()) {
        QMessageBox::warning(this, "查询错误", "获取包裹总数失败: " + countQuery.lastError().text());
        return;
    }

    if (countQuery.next()) {
        totalItems = countQuery.value(0).toInt();
    }

    // Calculate offset based on current page
    int offset = (currentPage - 1) * pageSize;

    // Main query with pagination
    QSqlQuery query(sqlDb);
    query.prepare("SELECT package_id, sender_name, recipient_name, status, claim_code "
                  "FROM packages ORDER BY package_id LIMIT :limit OFFSET :offset");
    query.bindValue(":limit", pageSize);
    query.bindValue(":offset", offset);

    if (!query.exec()) {
        QMessageBox::warning(this, "查询错误", "查询包裹数据失败: " + query.lastError().text());
        return;
    }

    int row = 0;
    while (query.next()) {
        long package_id = query.value(0).toLongLong();
        QString sender = query.value(1).toString();
        QString recipient = query.value(2).toString();
        int status = query.value(3).toInt();
        QString claim_code = query.value(4).toString();

        // Convert status to readable text
        QString statusText;
        switch (status) {
        case 1: statusText = "运输中"; break;
        case 2: statusText = "待入库"; break;
        case 3: statusText = "待取件"; break;
        case 4: statusText = "已取件"; break;
        case 5: statusText = "异常单"; break;
        default: statusText = "未知单"; break;
        }

        // Add data to model
        model->setItem(row, 0, new QStandardItem(QString::number(package_id)));
        model->setItem(row, 1, new QStandardItem(sender));
        model->setItem(row, 2, new QStandardItem(recipient));
        model->setItem(row, 3, new QStandardItem(statusText));
        model->setItem(row, 4, new QStandardItem(claim_code));

        row++;
    }

    // Update pagination controls
    updatePagination();

    ui->ListTable->resizeColumnsToContents();
}

// Load orders into table with pagination
void managerswin::loadOrdersIntoTable()
{
    // Set current table
    currentTable = "orders";

    // Clear the model
    model->clear();

    // Set headers
    QStringList headers;
    headers << "订单ID" << "包裹ID" << "用户名" << "取件方式" << "配送方式"
            << "原价" << "会员折扣" << "优惠券折扣" << "最终价格" << "优惠码";
    model->setHorizontalHeaderLabels(headers);

    // First query to get total count
    QSqlQuery countQuery(sqlDb);
    countQuery.prepare("SELECT COUNT(*) FROM orders");

    if (!countQuery.exec()) {
        QMessageBox::warning(this, "查询错误", "获取订单总数失败: " + countQuery.lastError().text());
        return;
    }

    if (countQuery.next()) {
        totalItems = countQuery.value(0).toInt();
    }

    // Calculate offset based on current page
    int offset = (currentPage - 1) * pageSize;

    // Main query with pagination
    QSqlQuery query(sqlDb);
    query.prepare("SELECT * FROM orders ORDER BY order_id LIMIT :limit OFFSET :offset");
    query.bindValue(":limit", pageSize);
    query.bindValue(":offset", offset);

    if (!query.exec()) {
        QMessageBox::warning(this, "查询错误", "查询订单数据失败: " + query.lastError().text());
        return;
    }

    int row = 0;
    while (query.next()) {
        int order_id = query.value(0).toInt();
        long package_id = query.value(1).toLongLong();
        QString username = query.value(2).toString();
        int pickup_method = query.value(3).toInt();
        int delivery_method = query.value(4).toInt();
        double original_price = query.value(5).toDouble();
        double member_discount = query.value(6).toDouble();
        double coupon_discount = query.value(7).toDouble();
        double final_price = query.value(8).toDouble();
        QString coupon_code = query.value(9).toString();

        // Convert methods to readable text
        QString pickupText = pickup_method == 1 ? "自取" : "配送";

        QString deliveryText;
        switch (delivery_method) {
        case 1: deliveryText = "普通"; break;
        case 2: deliveryText = "加急"; break;
        case 3: deliveryText = "特快"; break;
        default: deliveryText = "未知"; break;
        }

        // Add data to model
        model->setItem(row, 0, new QStandardItem(QString::number(order_id)));
        model->setItem(row, 1, new QStandardItem(QString::number(package_id)));
        model->setItem(row, 2, new QStandardItem(username));
        model->setItem(row, 3, new QStandardItem(pickupText));
        model->setItem(row, 4, new QStandardItem(deliveryText));
        model->setItem(row, 5, new QStandardItem(QString::number(original_price, 'f', 2)));
        model->setItem(row, 6, new QStandardItem(QString::number(member_discount, 'f', 2)));
        model->setItem(row, 7, new QStandardItem(QString::number(coupon_discount, 'f', 2)));
        model->setItem(row, 8, new QStandardItem(QString::number(final_price, 'f', 2)));
        model->setItem(row, 9, new QStandardItem(coupon_code));

        row++;
    }

    // Update pagination controls
    updatePagination();

    ui->ListTable->resizeColumnsToContents();
}

// Load users into table with pagination
void managerswin::loadUsersIntoTable()
{
    // Set current table
    currentTable = "users";

    // Clear the model
    model->clear();

    // Set headers
    QStringList headers;
    headers << "用户名" << "密码" << "类型" << "电话号码" << "会员等级" << "会员积分";
    model->setHorizontalHeaderLabels(headers);

    // Load users from file using C function
    struct users *head = loadUsersFromFile("users.txt");
    if (head == NULL) {
        QMessageBox::warning(this, "错误", "无法加载用户数据");
        return;
    }

    // Count total users
    totalItems = 0;
    struct users *countCurrent = head;
    while (countCurrent != NULL) {
        totalItems++;
        countCurrent = countCurrent->next;
    }

    // Calculate start and end indices for the current page
    int startIndex = (currentPage - 1) * pageSize;
    int endIndex = startIndex + pageSize;

    // Iterate to the starting position
    struct users *current = head;
    for (int i = 0; i < startIndex && current != NULL; i++) {
        current = current->next;
    }

    // Add users for the current page to the model
    int row = 0;
    while (current != NULL && row < pageSize) {
        // Convert user type to readable text
        QString typeText;
        switch (current->type) {
        case 1: typeText = "管理员"; break;
        case 2: typeText = "员工"; break;
        case 3: typeText = "用户"; break;
        default: typeText = "未知"; break;
        }

        // Add data to model
        model->setItem(row, 0, new QStandardItem(QString(current->username)));
        model->setItem(row, 1, new QStandardItem(QString(current->password)));
        model->setItem(row, 2, new QStandardItem(typeText));
        model->setItem(row, 3, new QStandardItem(QString(current->phonenumber)));
        model->setItem(row, 4, new QStandardItem(QString::number(current->members.level)));
        model->setItem(row, 5, new QStandardItem(QString::number(current->members.points)));

        current = current->next;
        row++;
    }

    // Free memory
    freeUsers(head);

    // Update pagination controls
    updatePagination();

    ui->ListTable->resizeColumnsToContents();
}

// Button click handlers
void managerswin::on_ListPackageBtn_clicked()
{
    currentPage = 1;  // Reset to first page when switching tables
    loadPackagesIntoTable();
}

void managerswin::on_ListOrderBtn_clicked()
{
    currentPage = 1;  // Reset to first page when switching tables
    loadOrdersIntoTable();
}

void managerswin::on_ListUserBtn_clicked()
{
    currentPage = 1;  // Reset to first page when switching tables
    loadUsersIntoTable();
}


// Placeholder implementations for other buttons - to be implemented later
void managerswin::on_UserSearchBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "用户查找与修改功能");
}

void managerswin::on_AddUserBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "添加用户功能");
}

void managerswin::on_InputStorageBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "快递入库功能");
}

void managerswin::on_OutputStorageBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "快递出库功能");
}

void managerswin::on_PackageSearchBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "包裹查询功能");
}

void managerswin::on_PriceChangeBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "计费变更功能");
}

void managerswin::on_DestinationChangeBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "目的地变更功能");
}

void managerswin::on_ViewNotificationBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "查看通知功能");
}

void managerswin::on_SendNotificationBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "发送通知功能");
}

void managerswin::on_operationhisButton_clicked()
{
    QMessageBox::information(this, "功能提示", "查询操作历史功能");
}

void managerswin::on_IssueCouponBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "发放优惠券功能");
}

void managerswin::on_ViewAndChangeCouponBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "查询与修改优惠券功能");
}

void managerswin::on_SearchOrderBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "查询订单功能");
}

void managerswin::on_ChangeOrderBtn_clicked()
{
    QMessageBox::information(this, "功能提示", "修改订单功能");
}
